package com.mediacloud.app.newsmodule.activity;


import static com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig.getAppServerConfigInfo;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.chinamcloud.collect.AcquisitionManager;

import com.ctrlvideo.ivplayer2.IVCtrlPlayer;
import com.ctrlvideo.ivplayer2.IVCtrlPlayerError;
import com.ctrlvideo.ivplayer2.IVCtrlPlayerListener;
import com.ctrlvideo.ivplayer2.playerview.ExoPlayerView;
import com.ctrlvideo.ivplayer2.playerview.IVPlayerView;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.model.eventbus.control.VideoDetailControl;
import com.mediacloud.app.model.eventbus.event.LoginEvent;
import com.mediacloud.app.model.eventbus.event.VideoDetailEvent;
import com.mediacloud.app.model.eventbus.mdoel.afpvideo.AppVideoAdItem;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.IntegralConfig;
import com.mediacloud.app.model.news.ReadDataReciver;
import com.mediacloud.app.model.news.ShowSwitch;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.broadcast.PowerStateReciver;
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoVodDetailFragment;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DisplayCutoutManager;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.share.IShareWrap;
import com.mediacloud.app.newsmodule.utils.share.OnScreenShotListener;
import com.mediacloud.app.newsmodule.utils.share.PosterShareWrap;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.reslib.analysis.AnalysisUtils;
import com.mediacloud.app.reslib.config.NewsDetailStyleConfig;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.ListStyle;
import com.mediacloud.app.user.model.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedHashSet;
import java.util.List;


public class InteractVideoDetailActivity extends StyleSetActivity implements DataInvokeCallBack<ArticleItemReciver>, OnScreenShotListener {
    public IVCtrlPlayer player;
    public FrameLayout playerLayout;
    NewsDetailInvoker newsDetailInvoker;
    ImageView fullscreen;
    ImageView ivMore;
    public ShareWrap shareWrap;//播放器更多

    protected Handler handler = new RecommendClickHandle();
    VideoVodDetailFragment fragment;
    boolean isOutView = false;
    PowerStateReciver powerStateReciver;
    ShowSwitch showSwitch;
    VideoDetailControl videoDetailControl;
    LinearLayout broccoliLayout;
    View vodBottomContent;
    private View mErrorView;
    private ImageView imagNowork;
    long mTyReportStartTime = 0;
    long mTyReportEndTime = 0;

    @Override
    public boolean showTitleBar() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        videoDetailControl = new VideoDetailControl();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        super.onCreate(savedInstanceState);

        catalogItem = getIntent().getParcelableExtra("catalog");
        articleItem = getIntent().getParcelableExtra("data");
        if (articleItem != null) {
            readStatus();
            showSwitch = articleItem.getmShowSwitch();
        }
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
        }
        fullscreen = Utility.findViewById(mRootView, R.id.fullscreen);
        ivMore = Utility.findViewById(mRootView, R.id.ivMore);
        vodBottomContent = Utility.findViewById(mRootView, R.id.vodBottomContent);
        broccoliLayout = Utility.findViewById(mRootView, R.id.broccoliLayout);
        boolean isLeftImgMode = ListStyle.TotoalStyle.LEFT_IMAGE.equals(serverAppConfigInfo.getContent_list());
        if (isLeftImgMode) {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli21, null));
            }
        } else {
            for (int i = 0; i < 3; i++) {
                broccoliLayout.addView(LayoutInflater.from(this).inflate(R.layout.layout_broccoli22, null));
            }
        }
        playerLayout = Utility.findViewById(mRootView, R.id.playerLayout);
        player = Utility.findViewById(mRootView, R.id.player);
        player.setAutoPlay(true);
        mErrorView = Utility.findViewById(mRootView, R.id.error_view);
        imagNowork = mErrorView.findViewById(R.id.image_loading);
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.net_not_give_force);
        String network = serverAppConfigInfo.getNetwork();
        FunKt.load(imagNowork, network, drawable);
        newsDetailInvoker = new NewsDetailInvoker(this);

        if (articleItem == null)
            return;
        fragment = new VideoVodDetailFragment();
        LinkedHashSet<String> linkedHashSet = getAppServerConfigInfo(this).getNewsDetailConfig().getLinkedHashSet();
        if(!linkedHashSet.contains(NewsDetailStyleConfig.COLLECT_BUTTON) && !linkedHashSet.contains(NewsDetailStyleConfig.SHARE_BUTTON)){
            ivMore.setVisibility(View.GONE);
        }else {
            ivMore.setVisibility(View.VISIBLE);
        }

        KillMusicUtils.stopAPS(this);
        getVideoDetail();


        powerStateReciver = new PowerStateReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        registerReceiver(powerStateReciver, intentFilter);
        setTitle("");


        onPageStart();
        showPageTransition();
        //设置使用刘海屏幕区域
        new DisplayCutoutManager(this).set(WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES);

        swipeBackLayout.setSupportSwipe(false);
        fullscreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setSelected(!v.isSelected());
                if (v.isSelected()) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    ViewGroup.LayoutParams lp = playerLayout.getLayoutParams();
                    lp.height = Utility.getScreenHeight(InteractVideoDetailActivity.this);
                    lp.width = Utility.getScreenWidth(InteractVideoDetailActivity.this);
                    vodBottomContent.setVisibility(View.GONE);
                    bottomBarLayout.setVisibility(View.GONE);
                    playerLayout.setLayoutParams(lp);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    ViewGroup.LayoutParams lp = playerLayout.getLayoutParams();
                    lp.height = getResources().getDimensionPixelSize(R.dimen.dimen220);
                    lp.width = Utility.getScreenWidth(InteractVideoDetailActivity.this);
                    vodBottomContent.setVisibility(View.VISIBLE);
                    bottomBarLayout.setVisibility(View.VISIBLE);
                    playerLayout.setLayoutParams(lp);
                }
            }
        });
        shareWrap = new ShareWrap(InteractVideoDetailActivity.this, false);
        ivMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                shareWrap.setShowFunction(true);
                shareWrap.init(articleItem, new CatalogItem());
                ((PosterShareWrap) shareWrap.getShare()).setOnScreenShotListener(InteractVideoDetailActivity.this);
                shareWrap.show(mRootView);
            }
        });

        judgeInteval();
        AddMedalStatistics.addMedalStatistics(this);//勋章统计
    }


    IntegralConfig config;
    boolean openInteval = false;//是否开启积分任务
    boolean openGrow = false;//是否开启成长值任务
    int timeInteval = 0;//增加积分时间（分）
    int timeGrow = 0;//增加成长值时间（分）

    //判断是否开启积分和无和成长任务
    private void judgeInteval() {
        config = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.integralConfig;
        if (config != null) {
            if (config.enableList1 != null && config.enableList1.size() != 0) {
                for (int i = 0; i < config.enableList1.size(); i++) {
                    if (config.enableList1.get(i) == 8) {
                        openInteval = true;
                        timeInteval = config.videoLeastDuration1;
                    }
                }
            }

            if (config.enableList4 != null && config.enableList4.size() != 0) {
                for (int i = 0; i < config.enableList4.size(); i++) {
                    if (config.enableList4.get(i) == 8) {
                        openGrow = true;
                        timeGrow = config.videoLeastDuration4;
                    }
                }
            }
        }
    }


    public ArticleItem getArticleItem() {
        return articleItem;
    }

    @Override
    protected boolean getFitSystemWindow() {
        return true;
    }


    Object mark = System.currentTimeMillis();


    protected void getVideoDetail() {

        CatalogItem catalogItem = getIntent().getParcelableExtra("catalog");
        if (catalogItem == null) {
            catalogItem = new CatalogItem();
            String nid = getIntent().getStringExtra("navigate_id");
            if (nid == null) {
                nid = "";
            }
            catalogItem.setCatid(nid);
        }
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        UserInfo info = UserInfo.getUserInfo(getBaseContext());
        videoDetailControl.getVideoDetail("" + articleItem.getId(), navigate_id, info.getUserid(), mark);
    }


    @Override
    public void onBackPressed() {
        if (shareWrap != null && shareWrap.isShowing()) {
            shareWrap.dismiss();
            isOutView = false;
        }
        if (fullscreen.isSelected()) {
            fullscreen.setSelected(!fullscreen.isSelected());
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            ViewGroup.LayoutParams lp = playerLayout.getLayoutParams();
            lp.height = getResources().getDimensionPixelSize(R.dimen.dimen220);
            lp.width = Utility.getScreenWidth(InteractVideoDetailActivity.this);
            vodBottomContent.setVisibility(View.VISIBLE);
            bottomBarLayout.setVisibility(View.VISIBLE);
            playerLayout.setLayoutParams(lp);
        } else {
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.release();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player.isPlaying()) {
            player.pause();
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis();
        }
        if (readStatusInvoker != null)
            readStatusInvoker.destory();
        readStatusInvoker = null;
        if (videoDetailControl != null) {
            videoDetailControl.dispose();
            videoDetailControl = null;
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        saveViewHistory();
        if (newsDetailInvoker != null) {
            newsDetailInvoker.destory();
        }

        try {
            unregisterReceiver(powerStateReciver);
            if (fragment != null) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.remove(fragment);
                transaction.commitNowAllowingStateLoss();
            }
        } catch (Exception ex) {
        }
    }

    @Override
    public int getStatusBarColor() {
        return Color.BLACK;
    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_activity_interact_detail;
    }

    @Override
    public void onScreenShot() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ViewGroup.LayoutParams lp = playerLayout.getLayoutParams();
        lp.height = getResources().getDimensionPixelSize(R.dimen.dimen220);
        lp.width = Utility.getScreenWidth(InteractVideoDetailActivity.this);
        vodBottomContent.setVisibility(View.VISIBLE);
        bottomBarLayout.setVisibility(View.VISIBLE);
        playerLayout.setLayoutParams(lp);
        fullscreen.setSelected(false);

        playerLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    IVPlayerView ivPlayerView = player.ivPlayerView;
                    if (ivPlayerView instanceof ExoPlayerView) {
                        TextureView textureView = (TextureView) ((ExoPlayerView) ivPlayerView).playerView.getVideoSurfaceView();
                        Bitmap bitmap = textureView.getBitmap();
                        IShareWrap iShareWrap = shareWrap.getShare();

                        shareWrap.show(mRootView);
                        if (iShareWrap instanceof PosterShareWrap) {
                            ((PosterShareWrap) iShareWrap).sharScreenShot(bitmap);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 400);


    }


    protected class RecommendClickHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //分享
            if (msg.what == 0) {
                return;
            }
            //点赞
            else if (msg.what == 100) {
                fragment.setVideoReades(msg.arg1);
            }
            try {
                ArticleItem articleItem = (ArticleItem) msg.obj;
                if (articleItem == null) return;
                if (articleItem.getId() == articleItem.getId())
                    return;
                saveViewHistory();
                getVideoDetail();
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "" + e.getMessage());
            }
        }
    }


    protected void deleteHistoryPosition() {
        //  VideoSeekKit.clearHisSeek(""+articleItem.getId());
    }

    public void saveViewHistory() {
        if (!player.isPlaying()) {
            deleteHistoryPosition();
        } else if (player.getCurrentPosition() > 0 && player.getCurrentPosition() < player.getDuration()) {
            addViewHistory(player.getCurrentPosition());
        }
    }

    protected void addViewHistory(long position) {

        //  VideoSeekKit.addHisSeek(""+articleItem.getId(),position);
    }

    public String mp4Data;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reciveVideoDetail(VideoDetailEvent<List<AppVideoAdItem>, ArticleItemReciver> event) {
        if (event.getType() != VideoDetailEvent.ResultDetail && event.getData().otherData != mark)
            return;

        success(event.getData());
    }


    @Override
    public void success(ArticleItemReciver data) {

        if (data.state && data.articleItem != null) {
            if (articleItem != null && articleItem.getId() == data.articleItem.getId()) {
                mTyReportEndTime = mTyReportStartTime = System.currentTimeMillis();
            }
            articleItem = data.articleItem;
            sendExposureEvent();
            refreshBottomStyle(data.articleItem, 1);
            UserRecommend.addItemKeyWord(articleItem, this);
            articleItem.mShowSwitch = showSwitch;
            if (hadAdded) {
                fragment.setArticleItem(articleItem);
            }

            initDetailFragment(data, true);
            setVideoContent(articleItem.getProp1());

        }
        AddMedalStatistics.addMedalStatistics(this); //勋章统计
        startAddIntegralCounter();
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null) {
                    return;
                }
                Addintegral.addintegral(InteractVideoDetailActivity.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0", articleItem);
            }
        });

        //开启视频任务时
        if (openInteval) {
            AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
                @Override
                public void timeoutCallback() {
                    if (articleItem == null) {
                        return;
                    }
                    Addintegral.addintegral(InteractVideoDetailActivity.this, articleItem.getId(), 8, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0", openGrow, articleItem);
                }
            }, Math.min(timeInteval, timeGrow),AddIntegralCounter.VideoTask);
        }

    }

    private void setVideoContent(String pid) {
        player.loadIVideoPid(/*"5WsZ25nhK0U84172"*/pid, new IVCtrlPlayerListener() {
            @Override
            public void onError(IVCtrlPlayerError error) {
                IVCtrlPlayerListener.super.onError(error);
            }
        });

    }

    public void hiddBroccoliLayout() {
        broccoliLayout.setVisibility(View.GONE);
        mErrorView.setVisibility(View.GONE);
    }

    boolean hadAdded = false;

    protected void initDetailFragment(ArticleItemReciver data, boolean appfacBuy) {
        if (hadAdded)
            return;
        Bundle args = new Bundle();
        args.putParcelable("data", data.articleItem);
        args.putParcelable("catalog", catalogItem);
        args.putBoolean("appfacBuy", appfacBuy);
        args.putParcelableArrayList("components", data.components);
        fragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.vodBottomContent, fragment);
        transaction.show(fragment);
        transaction.commitAllowingStateLoss();
        hadAdded = true;
    }

    @Override
    public void fault(Object data) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

    }

    ReadStatusInvoker readStatusInvoker;

    public void readStatus() {
        readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<ReadDataReciver>() {
            @Override
            public void success(ReadDataReciver data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, data.virtualIncrement);
                Message msg = new Message();
                msg.what = 100;
                msg.arg1 = (int) data.reads;
                handler.sendMessageDelayed(msg, 2000);
            }

            @Override
            public void fault(Object data) {
                AnalysisUtils.readsAnalysis(getApplicationContext(), articleItem, AnalysisUtils.DefaultVirtualIncrement);
            }
        });
        readStatusInvoker.readStatistics(articleItem.getId() + "", 1);
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (articleItem != null) {
            UserInfo info = UserInfo.getUserInfo(this);
            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent loginEvent) {
        //20200117修复登录后页面不刷新导致无法更新付费状态的bug
        if (UserInfo.getUserInfo(this).isLogin()) {
            getVideoDetail();
        }
    }

    @Override
    public void noNetwork() {
        mErrorView.setVisibility(View.VISIBLE);
        //  emptyTipsText.setText("网络请求失败，请点击重试");
        mErrorView.setOnClickListener(v -> {
            if (hasNetWork)
                getVideoDetail();
            else showNetWorDialog();
        });
    }
}